package com.llw.testdemo;

import android.os.Bundle;
import android.view.KeyEvent;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.llw.mvplibrary.mvp.MvpActivity;
import com.llw.mvplibrary.utils.ObjectUtils;
import com.llw.testdemo.adapter.TestAdapter;
import com.llw.testdemo.bean.TestResponse;
import com.llw.testdemo.contract.TestContract;
import com.llw.testdemo.utils.StatusBarUtil;
import com.llw.testdemo.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Response;

import static com.llw.testdemo.utils.Constant.JSON_DATA;
import static com.llw.testdemo.utils.Constant.SUCCESS_CODE;

public class MainActivity extends MvpActivity<TestContract.TestPresenter> implements TestContract.ITestView {

    @BindView(R.id.rv)
    RecyclerView rv;
    private List<TestResponse.DataBean> mList;
    private TestAdapter mAdapter;

    @Override
    public void initData(Bundle savedInstanceState) {
        StatusBarUtil.StatusBarLightMode(this);//高亮状态栏，字体黑色
        showLoadingDialog();//加载框
        initList();//初始化列表
        mPresent.testDataList(context);//业务请求
    }

    private void initList() {
        mList = new ArrayList<>();
        mAdapter = new TestAdapter(R.layout.item_test_list, mList);
        rv.setLayoutManager(new LinearLayoutManager(context));
        rv.setAdapter(mAdapter);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected TestContract.TestPresenter createPresent() {
        return new TestContract.TestPresenter();
    }

    //数据返回
    @Override
    public void getTestListResult(Response<TestResponse> response) {
        dismissLoadingDialog();
        if (response.body().getCode() == SUCCESS_CODE) {
            if (response.body().getData() != null && !ObjectUtils.isEmpty(response.body().getData())) {
                List<TestResponse.DataBean> dataBeans = response.body().getData();
                mList.clear();//添加数据之前先清除
                mList.addAll(dataBeans);//添加数据
                mAdapter.notifyDataSetChanged();//刷新列表
            } else {
                ToastUtils.showShortToast(context, "接收数据为空");
            }
        } else {
//            ToastUtils.showShortToast(context, response.body().getMsg());
            Gson gson = new Gson();
            TestResponse testResponse = gson.fromJson(JSON_DATA, TestResponse.class);
            List<TestResponse.DataBean> dataBeans = testResponse.getData();
            mList.clear();
            mList.addAll(dataBeans);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void getDataFailed() {
        dismissLoadingDialog();
        ToastUtils.showShortToast(context, "连接超时，请稍后尝试！");
    }


}
